package de.elmar_baumann.jbirthdays.ui;

import de.elmar_baumann.jbirthdays.api.Person;
import de.elmar_baumann.jbirthdays.util.Bundle;
import de.elmar_baumann.jbirthdays.util.DateUtil;
import de.elmar_baumann.jbirthdays.util.Mnemonics;
import de.elmar_baumann.jbirthdays.util.StringUtil;
import java.util.Calendar;
import javax.swing.JOptionPane;
import javax.swing.text.JTextComponent;

/**
 * @author Elmar Baumann
 */
public class EditPersonDialog extends Dialog {

    private static final long serialVersionUID = 1L;

    private boolean accepted;
    private final Person person;

    public EditPersonDialog(Dialog owner) {
        this(owner, new Person());
    }

    public EditPersonDialog(Dialog owner, Person person) {
        super(owner, true);
        if (person == null) {
            throw new NullPointerException("person == null");
        }
        this.person = person;
        setModal(true);
        initComponents();
        postInitComponents();
    }

    private void postInitComponents() {
        Mnemonics.setMnemonics(this);
        Calendar todayCal = Calendar.getInstance();
        textFieldBirthdayYear.setInputVerifier(new NumberRangeInputVerifier(1800, todayCal.get(Calendar.YEAR)));
        textFieldBirthdayMonth.setInputVerifier(new NumberRangeInputVerifier(1, 12));
        textFieldBirthdayDay.setInputVerifier(new NumberRangeInputVerifier(1, 31));
        personToGui();
    }

    private void personToGui() {
        textFieldFirstName.setText(StringUtil.nullToEmptyString(person.getFirstName()));
        textFieldLastName.setText(StringUtil.nullToEmptyString(person.getLastName()));
        textFieldEmail.setText(StringUtil.nullToEmptyString(person.getEmail()));
        setInt(textFieldBirthdayYear, person.getBirthdayYear());
        setInt(textFieldBirthdayMonth, person.getBirthdayMonth());
        setInt(textFieldBirthdayDay, person.getBirthdayDay());
        textAreaNotes.setText(StringUtil.nullToEmptyString(person.getNotes()));
        checkBoxNotify.setSelected(person.isNotify());
    }

    public Person save() {
        if (inputsValid(false)) {
            person.setFirstName(textFieldFirstName.getText().trim());
            person.setLastName(textFieldLastName.getText().trim());
            person.setEmail(textFieldEmail.getText().trim());
            person.setBirthdayYear(toInt(textFieldBirthdayYear));
            person.setBirthdayMonth(toInt(textFieldBirthdayMonth));
            person.setBirthdayDay(toInt(textFieldBirthdayDay));
            person.setNotes(textAreaNotes.getText());
            person.setNotify(checkBoxNotify.isSelected());
        }
        return person;
    }

    private void setInt(JTextComponent tc, int i) {
        String text = i > 0
                ? Integer.toString(i)
                : "";
        tc.setText(text);
    }

    private int toInt(JTextComponent tc) {
        String text = tc.getText().trim();
        return text.isEmpty()
                ? 0
                : Integer.parseInt(text);
    }

    private boolean inputsValid(boolean errorMessage) {
        boolean valid = StringUtil.hasContent(textFieldLastName.getText())
                && DateUtil.maybeDate(toInt(textFieldBirthdayMonth), toInt(textFieldBirthdayDay));
        if (!valid && errorMessage) {
            JOptionPane.showMessageDialog(this,
                    Bundle.getString(EditPersonDialog.class, "EditPersonDialog.ErrorMessage.InvalidInput"),
                    Bundle.getString(EditPersonDialog.class, "EditPersonDialog.ErrorMessage.InvalidInput.Title"),
                    JOptionPane.ERROR_MESSAGE);
        }
        return valid;
    }

    public boolean isAccepted() {
        return accepted;
    }

    private void ok() {
        if (inputsValid(true)) {
            accepted = true;
            dispose();
        }
    }

    private void cancel() {
        dispose();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        panelContent = new javax.swing.JPanel();
        labelFirstName = new javax.swing.JLabel();
        textFieldFirstName = new javax.swing.JTextField();
        labelLastName = new javax.swing.JLabel();
        textFieldLastName = new javax.swing.JTextField();
        labelEmail = new javax.swing.JLabel();
        textFieldEmail = new javax.swing.JTextField();
        panelDateOfBirth = new javax.swing.JPanel();
        labelBirthdayYear = new javax.swing.JLabel();
        textFieldBirthdayYear = new javax.swing.JTextField();
        labelBirthdayMonth = new javax.swing.JLabel();
        textFieldBirthdayMonth = new javax.swing.JTextField();
        labelBirthdayDay = new javax.swing.JLabel();
        textFieldBirthdayDay = new javax.swing.JTextField();
        labelNotes = new javax.swing.JLabel();
        scrollPaneNotes = new javax.swing.JScrollPane();
        textAreaNotes = new javax.swing.JTextArea();
        panelButtons = new javax.swing.JPanel();
        checkBoxNotify = new javax.swing.JCheckBox();
        buttonOk = new javax.swing.JButton();
        buttonCancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("de/elmar_baumann/jbirthdays/ui/Bundle"); // NOI18N
        setTitle(bundle.getString("EditPersonDialog.title")); // NOI18N
        getContentPane().setLayout(new java.awt.GridBagLayout());

        panelContent.setLayout(new java.awt.GridBagLayout());

        labelFirstName.setLabelFor(textFieldFirstName);
        labelFirstName.setText(bundle.getString("EditPersonDialog.labelFirstName.text")); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        panelContent.add(labelFirstName, gridBagConstraints);

        textFieldFirstName.setColumns(30);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0);
        panelContent.add(textFieldFirstName, gridBagConstraints);

        labelLastName.setLabelFor(textFieldLastName);
        labelLastName.setText(bundle.getString("EditPersonDialog.labelLastName.text")); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 0);
        panelContent.add(labelLastName, gridBagConstraints);

        textFieldLastName.setColumns(30);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 0);
        panelContent.add(textFieldLastName, gridBagConstraints);

        labelEmail.setLabelFor(textFieldEmail);
        labelEmail.setText(bundle.getString("EditPersonDialog.labelEmail.text")); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 0);
        panelContent.add(labelEmail, gridBagConstraints);

        textFieldEmail.setColumns(30);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 0);
        panelContent.add(textFieldEmail, gridBagConstraints);

        panelDateOfBirth.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle.getString("EditPersonDialog.panelDateOfBirth.border.title"))); // NOI18N

        labelBirthdayYear.setLabelFor(textFieldBirthdayYear);
        labelBirthdayYear.setText(bundle.getString("EditPersonDialog.labelBirthdayYear.text")); // NOI18N

        textFieldBirthdayYear.setColumns(4);

        labelBirthdayMonth.setLabelFor(textFieldBirthdayMonth);
        labelBirthdayMonth.setText(bundle.getString("EditPersonDialog.labelBirthdayMonth.text")); // NOI18N

        textFieldBirthdayMonth.setColumns(2);

        labelBirthdayDay.setLabelFor(textFieldBirthdayDay);
        labelBirthdayDay.setText(bundle.getString("EditPersonDialog.labelBirthdayDay.text")); // NOI18N

        textFieldBirthdayDay.setColumns(2);

        javax.swing.GroupLayout panelDateOfBirthLayout = new javax.swing.GroupLayout(panelDateOfBirth);
        panelDateOfBirth.setLayout(panelDateOfBirthLayout);
        panelDateOfBirthLayout.setHorizontalGroup(
            panelDateOfBirthLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelDateOfBirthLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(labelBirthdayYear)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(textFieldBirthdayYear, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(labelBirthdayMonth)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(textFieldBirthdayMonth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(labelBirthdayDay)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(textFieldBirthdayDay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        panelDateOfBirthLayout.setVerticalGroup(
            panelDateOfBirthLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelDateOfBirthLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelDateOfBirthLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelBirthdayYear)
                    .addComponent(textFieldBirthdayYear, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelBirthdayMonth)
                    .addComponent(textFieldBirthdayMonth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelBirthdayDay)
                    .addComponent(textFieldBirthdayDay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(7, 0, 0, 0);
        panelContent.add(panelDateOfBirth, gridBagConstraints);

        labelNotes.setLabelFor(textAreaNotes);
        labelNotes.setText(bundle.getString("EditPersonDialog.labelNotes.text")); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        panelContent.add(labelNotes, gridBagConstraints);

        textAreaNotes.setColumns(20);
        textAreaNotes.setLineWrap(true);
        textAreaNotes.setRows(5);
        textAreaNotes.setWrapStyleWord(true);
        scrollPaneNotes.setViewportView(textAreaNotes);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(7, 0, 0, 0);
        panelContent.add(scrollPaneNotes, gridBagConstraints);

        panelButtons.setLayout(new java.awt.GridBagLayout());

        checkBoxNotify.setText(bundle.getString("EditPersonDialog.checkBoxNotify.text")); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        panelButtons.add(checkBoxNotify, gridBagConstraints);

        buttonOk.setText(bundle.getString("EditPersonDialog.buttonOk.text")); // NOI18N
        buttonOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonOkActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        panelButtons.add(buttonOk, gridBagConstraints);

        buttonCancel.setText(bundle.getString("EditPersonDialog.buttonCancel.text")); // NOI18N
        buttonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonCancelActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0);
        panelButtons.add(buttonCancel, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 0);
        panelContent.add(panelButtons, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
        gridBagConstraints.gridheight = java.awt.GridBagConstraints.REMAINDER;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
        getContentPane().add(panelContent, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buttonOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonOkActionPerformed
        ok();
    }//GEN-LAST:event_buttonOkActionPerformed

    private void buttonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCancelActionPerformed
        cancel();
    }//GEN-LAST:event_buttonCancelActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(EditPersonDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                EditPersonDialog dialog = new EditPersonDialog(null);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonCancel;
    private javax.swing.JButton buttonOk;
    private javax.swing.JCheckBox checkBoxNotify;
    private javax.swing.JLabel labelBirthdayDay;
    private javax.swing.JLabel labelBirthdayMonth;
    private javax.swing.JLabel labelBirthdayYear;
    private javax.swing.JLabel labelEmail;
    private javax.swing.JLabel labelFirstName;
    private javax.swing.JLabel labelLastName;
    private javax.swing.JLabel labelNotes;
    private javax.swing.JPanel panelButtons;
    private javax.swing.JPanel panelContent;
    private javax.swing.JPanel panelDateOfBirth;
    private javax.swing.JScrollPane scrollPaneNotes;
    private javax.swing.JTextArea textAreaNotes;
    private javax.swing.JTextField textFieldBirthdayDay;
    private javax.swing.JTextField textFieldBirthdayMonth;
    private javax.swing.JTextField textFieldBirthdayYear;
    private javax.swing.JTextField textFieldEmail;
    private javax.swing.JTextField textFieldFirstName;
    private javax.swing.JTextField textFieldLastName;
    // End of variables declaration//GEN-END:variables

}
